package com.mashibing.servicemap.remote;

import com.mashibing.constant.AmapDirectionConstant;
import com.mashibing.dto.ForecastPrice;
import com.mashibing.responsse.DirectionResponse;
import com.sun.javafx.fxml.builder.URLBuilder;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

@Service
@Slf4j
public class AmapDirectionRemote {

    @Value("${amap.key}")
    private String amapKey;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 调用第三方服务获取距离和使用时长
     *1、配置访问url
     * 2、调用高德接口
     * 3、解析接口
     * https://restapi.amap.com/v3/direction/driving?origin=116.45925,39.910031&destination=116.587922,40.081577&output=xml&key=<用户的key>
     * @param forecastPrice
     * @return
     */
    public  Optional<DirectionResponse> direction (ForecastPrice forecastPrice){
        // 1、配置访问url
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(AmapDirectionConstant.DIRECTION_URL);
        stringBuilder.append("?");
        // 出发地经纬度
        stringBuilder.append("origin=" + forecastPrice.getDepLongitude() +"," + forecastPrice.getDepLatitude());
        stringBuilder.append("&");
        stringBuilder.append("destination=" + forecastPrice.getDestLongitude() +"," + forecastPrice.getDestLatitude());
        stringBuilder.append("&");
        stringBuilder.append("output=");
        stringBuilder.append("json");
        stringBuilder.append("&");
        stringBuilder.append("key=");
        stringBuilder.append(amapKey);
        stringBuilder.append("&");
        stringBuilder.append("strategy=" + AmapDirectionConstant.DEFAULT_STRATEGY);
        log.info(String.valueOf(stringBuilder));

        //2、调用高德接口
        ResponseEntity<String> directionEntity = restTemplate.getForEntity(stringBuilder.toString(), String.class);
        String directionEntityBody = directionEntity.getBody();
        log.info(directionEntityBody);

        //  3、解析接口
        Optional<DirectionResponse> directionResponse = parseDirectionEntity(directionEntityBody);
        return directionResponse;
    }

    /**
     * 解析高德返回路线规划数据
     * @param directionEntityBody
     * @return
     */
    public Optional<DirectionResponse> parseDirectionEntity (String directionEntityBody){
        // 定义接收对象
        DirectionResponse directionResponse = null;


        try {
        // 解析json
           JSONObject directionObject = JSONObject.fromObject(directionEntityBody);

           // 判断响应是否成功
          if (directionObject.has(AmapDirectionConstant.STATUS)){
               if (directionObject.getInt(AmapDirectionConstant.STATUS) == 1){
                   // 如果 驾车路径规划信息列表 存在
                    if (directionObject.has(AmapDirectionConstant.ROUTE)) {
                        JSONObject routeJsonObject = directionObject.getJSONObject(AmapDirectionConstant.ROUTE);
                        //如果 驾车换乘方案 存在
                        if (routeJsonObject.has(AmapDirectionConstant.PATHS)) {
                            // 创建新的响应对象
                            directionResponse  = new DirectionResponse();
                            // 解析
                            JSONArray pathJsonArray = routeJsonObject.getJSONArray(AmapDirectionConstant.PATHS);
                            // 获取 驾车换乘方案  第一个对象
                            JSONObject pathItemObject = pathJsonArray.getJSONObject(0);

                            // 获取行驶距离
                          if (pathItemObject.has(AmapDirectionConstant.DISTANCE)) {
                              int distance = pathItemObject.getInt(AmapDirectionConstant.DISTANCE);
                              directionResponse.setDistance(distance);
                          }
                          // 获取预计行驶时间
                          if (pathItemObject.has(AmapDirectionConstant.DURATION)) {
                              int duration = pathItemObject.getInt(AmapDirectionConstant.DURATION);
                              directionResponse.setDuration(duration);
                          }
                        }
                    }
              }
           }

       }catch (Exception e) {
           log.error("Error parsing direction entity", e);
       }

        return Optional.ofNullable(directionResponse);
    }



}
